package com.ling.springboottest.controller;


import com.ling.springboottest.entity.Book;
import com.ling.springboottest.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/book")
public class BookController {

    @Resource
    private BookRepository bookRepository;

    /**
     * 后端提供分页接口
     *  http://localhost:8181/book/findAll
     * @return
     */
    @GetMapping("/findAll/{page}/{size}")
    public Page<Book> findBookByPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        //第几页（0开始），每页取多少条
        Pageable pageable = PageRequest.of(page-1,size);

        // Pageable是接口，用它的实现类。
        // 页码从0开始。(0,6)表示查第1页数据，只取6条。

        Page<Book> page1 = bookRepository.findAll(pageable);
        return page1;
    }
    /**
     * 后端-添加图书接口
     *  http://localhost:8181/book/save
     * @return
     */
    @PostMapping ("/save")
    public String saveBook(@RequestBody Book book){

        Book book1 = bookRepository.save(book);
        if (book1 !=null){
            return "sucess";
        }else {
            return "error";
        }
    }

    /**
     * 后端-根据id获得Book对象接口
     *  http://localhost:8181/book/findById/1
     * @return
     */
    @GetMapping ("/findById/{id}")
    public Book findById(@PathVariable("id") Integer id){

        Optional<Book> book = bookRepository.findById(id);
        Book book1 = book.get();
        return book1;
    }
    /**
     * 后端-修改图书ById
     *  http://localhost:8181/book/updateBook + obj
     * @return
     */
    @PutMapping ("/updateBook")
    public String updateBook(@RequestBody Book book){
        Book book1 = bookRepository.save(book);
        System.out.println(book1);
        if (book1 !=null){
            return "sucess";
        }else {
            return "error";
        }
    }

    /**
     * 后端-删除图书ById
     *  http://localhost:8181/book/deleteBook/125
     * @return
     */
    @DeleteMapping  ("/deleteBook/{id}")
    public String deleteBook(@PathVariable Integer id){
        bookRepository.deleteById(id); //无返回值
        System.out.println(id + "delete ok" );

        return "sucess";
    }


    // http://localhost:8181/book/findAll
    @GetMapping("/findAll")
    public List<Book> findAll(){
        List<Book> bookList = bookRepository.findAll();
        return bookList;
    }

}
